import { ipcMain, IpcMainEvent } from 'electron';
import { listDevices, reconnectDevice, scanWirelessDevice } from '@/main/adb/utils';
import { AndroidDevice } from '@/main/adb/android-device';
import { QueryDeviceEvent } from '@/type/typings';

/** 上一次读取到的设备列表 */
let prevDevices: AndroidDevice[] = [];

const DEVICE_QUERY_SUCCESS = 'device-query-success';
const DEVICE_QUERY = 'device-query';

const RECONNECT_DEVICE = 'reconnect-device';
const RECONNECTED_DEVICE = 'reconnected-device';

const SCAN_DEVICES = 'scan-device';

export function startAdbService() {
  ipcMain.on(DEVICE_QUERY, queryDeviceListener);
  ipcMain.on(RECONNECT_DEVICE, reconnectDeviceListener);
  ipcMain.on(SCAN_DEVICES, scanDeviceListernr);
}

export function stopAdbService() {
  ipcMain.removeListener(DEVICE_QUERY, queryDeviceListener);
  ipcMain.removeListener(RECONNECT_DEVICE, reconnectDeviceListener);
  ipcMain.removeListener(SCAN_DEVICES, scanDeviceListernr);
}

async function queryDeviceListener({ sender }: IpcMainEvent) {
  const devices = await listDevices();
  let hasChange = false;

  if (devices.length !== prevDevices.length) {
    // 两者长度不一致, 说明插入电脑的设备数量发生变化
    prevDevices = devices;
    hasChange = true;
  } else {
    if (devices.length > 0) {
      // 判断设备ID和设备状态是否发生改变
      for (const device of devices) {
        const finded = prevDevices.find(d => d.id === device.id);
        // 新读取到的设备不存在于上一次读到的设备列表中,或者设备状态发生改变了
        if (!finded || finded.status !== device.status) {
          prevDevices = devices;
          hasChange = true;
          break;
        }
      }
    }
  }

  sender.send(DEVICE_QUERY_SUCCESS, {
    changed: hasChange,
    devices: hasChange ? devices : undefined
  } as QueryDeviceEvent);
}

async function reconnectDeviceListener({ sender }: IpcMainEvent, { deviceId }: { deviceId: string }) {
  try {
    await reconnectDevice(deviceId);
  } catch (e) {
  } finally {
    sender.send(RECONNECTED_DEVICE);
  }
}

async function scanDeviceListernr({ sender }: IpcMainEvent) {
  await scanWirelessDevice({
    onprocess(event) {
      sender.send('scan-process', event);
    },
    onend(event) {
      sender.send('scan-end', event);
    }
  });
}
